const moment = require('../../utils/moment.min')
Page({
  data: {
    result: [],
    isInit: true,
    dict: {
      '1': {
        label: '双',
        color: 'orange'
      },
      '0': {
        label: '单',
        color: 'gray'
      },
      '-1': {
        label: '和',
        color: 'blue'
      }
    },
    current: null
  },
  onLoad() {
    let date = moment()
    this.loadData(date)
    this.setData({
      current: date
    })
  },
  onPullDownRefresh: function () {
    // 下拉刷新
    this.setData({
      isInit: true
    })
    this.loadData(moment())
  },
  onReachBottom() {
    this.next()
  },
  tap() {
    this.next()
  },
  next() {
    let current = this.data.current.subtract(1, 'days')
    
    this.setData({
      current: current,
      isInit: false
    })
    this.loadData(current)
  },
  loadData(date) {
    let dateStr = date.format('YYYY-MM-DD')
    wx.request({
      url: `https://ig185.com/kaijiangweb/getHistoryList.do?date=${dateStr}&lotCode=GD115`,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      success: (res) => {
        wx.stopPullDownRefresh()
        // console.log(res.data.result)
        let origin = this.data.result
        if (this.data.isInit) {
          origin = []
        }
        let result = origin.concat(res.data.result)
        // 统计单与双的个数
        let single = 0
        let double = 0
        let draw = 0
        let singleNearby = 0
        let doubleNearby = 0
        let drawNearby = 0
        result.forEach(item => {
          switch (item.firstSingleDouble) {
            case 1:
              double++
              break;
            case 0:
              single++
              break;
            default:
              draw++
              break;
          }
        })
        result.filter((item, index) => {
          return index < 15
        }).forEach(item => {
          // console.log(item)
          switch (item.firstSingleDouble) {
            case 1:
              doubleNearby++
              break;
              case 0:
              singleNearby++
              break;
            default:
              drawNearby++
              break;
          }
        })
        this.setData({
          result: result.map(item => {
            item.time = moment(item.preDrawTime).format('DD日 HH:mm')
            item.issue = item.preDrawIssue.substring(8)
            if (item.issue.indexOf('0') === 0) {
              item.issue = item.issue.substring(1)
            }
            return item
          }),
          single: single,
          double: double,
          win: single - double,
          draw: draw,
          singleNearby: singleNearby,
          doubleNearby: doubleNearby,
          drawNearby: drawNearby,
          winNearby: singleNearby - doubleNearby,
          loadingTip: res.data.result.length == 0 ? '已经没有更多啦' : '上拉加载更多'
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })
  }
})